#!/usr/bin/python3

import json
import urllib
import http.client
import requests

import socket
import sys
import os
import subprocess

# 房间号
os_roomid = "null"

# 获取推流地址api
urlStream = "https://gw.sit.qiuhui.com/jmfen-live/v0.1/streams/publishAddr/TC/"
urlStream_s = "https://gw.sit.qiuhui.com/jmfen-live/v0.1/streams/publishAddr/TC/"
urlStream_p = "https://gw.qiuhui.com/jmfen-live/v0.1/streams/publishAddr/TC/"

filePath_windows = "\\20191001-20200103.flv"

# 通过uid和token获取推流地址
def getPushStreamUrl() :
    urlStreamL = urlStream + os_roomid
    print("获取推流地址 ",urlStreamL)
    res = requests.get(urlStreamL)
    print("INDEX 0",res)
    print("INDEX 1",res.text)

    # json_str = json.dumps(res.text) #多余了
    # print("INDEX 2",json_str)

    json_data = json.loads(res.text)
    print("INDEX 3",json_data['data']['url'])
    return json_data['data']['url']

def checkVideoResolution(check_videofile) :
    commandCheck = os.path.dirname( sys.argv[0] ) + "\\ffprobe.exe -loglevel quiet -print_format json -show_format -show_streams -select_streams v -i " + "\"" + os.path.dirname( sys.argv[0] ) + "\\VideoFile" + "\\" + check_videofile + "\""
    resultCheck = subprocess.Popen(commandCheck,shell=True,stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
    out = resultCheck.stdout.read()
    temp = str(out.decode('utf-8'))

    json_data = json.loads(temp)
    widthCheck = json_data['streams'][0]['width']
    heightCheck = json_data['streams'][0]['height']
    if 1920 == widthCheck and 1080 == heightCheck :
        return 0
    else :
        return 1

# 读取video文件夹中所有文件并循环推流
def doPushStream2() :
    print("启动循环推流")
    while 1:
        pushUrl = getPushStreamUrl()
        print("推流地址：",pushUrl)
        videofilepath = os.path.dirname( sys.argv[0] ) + "\\VideoFile"
        print("推流文件夹为：",videofilepath)
        videofilenames = os.listdir(videofilepath)
        
        for file in videofilenames:
            print("目前推流文件为：",file)
            ret = checkVideoResolution(file)
            #print(ret)
            #aa = input("断点")
            
            if 0 == ret:
                command = os.path.dirname( sys.argv[0] ) + "\\ffmpeg.exe -re -i " + "\"" + videofilepath + "\\" + file + "\"" + " -c copy -f flv " + "\"" + pushUrl + "\""
            else :
                command = os.path.dirname( sys.argv[0] ) + "\\ffmpeg.exe -re -i " + "\"" + videofilepath + "\\" + file + "\"" + " -c:v libx264 -s 1920x1080 -c:a copy -f flv " + "\"" + pushUrl + "\""
            print("指令为：",command)
            resL = os.system(command)
            print("该文件推送完毕：",file,"；返回值为：",resL)
    print("结束推流")
    return

# 执行推流 -- 推流中断后重新获取推流 
def doPushStream() :
    print("启动循环推流")
    while 1:
        pushUrl = getPushStreamUrl()
        print("INDEX 4",pushUrl)
        # 先替换 再设置前后
        #badstr = pushUrl[pushUrl.rfind("/")+1:pushUrl.rfind("?")]
        #print("INDEX 4-1",badstr)

        #pushUrl = pushUrl.replace(badstr,str(os_roomid))
        #print("INDEX 4-2",pushUrl)

        #pushUrl_0 = "\"" + pushUrl + "\""
        #print("INDEX 4-3",pushUrl_0)

        #command = "ffmpeg -stream_loop -1 -re -i "+ filePath + " -c copy -f flv " + "rtmp://192.168.33.8/live/ch"
        #command = os.path.dirname( sys.argv[0] ) + "\\ffmpeg.exe -stream_loop -1 -re -i "+ os.path.dirname( sys.argv[0] ) + filePath_windows + " -c copy -f flv " + "\"" + pushUrl + "\""
        command = os.path.dirname( sys.argv[0] ) + "\\ffmpeg.exe -stream_loop -1 -re -i " + "\"" + filePath_windows + "\"" + " -c copy -f flv " + "\"" + pushUrl + "\""
        print("INDEX 5",command)

        resL = os.system(command) # 接口返回的地址改换末端值后 推流被服务器拒绝
        print("INDEX 6",resL)
        
        print("结束推流")
    return


if __name__ == '__main__':
    print("###############################")
    print(" 注意: 默认推流画面为1920X1080 \n")
    ##
    os_roomid = input("设置主播房间号：")
    print ("主播房间号为:",os_roomid)
    
    #filePath_windows = input("设置推流文件：")
    #print ("推流文件为:",filePath_windows)

    inputstr = input("选择推送的环境(s 或 p)：")
    if 's' == inputstr:
        print ("\n你选择的环境为: sit")
        urlStream = urlStream_s
    if 'p' == inputstr:
        print ("\n你选择的环境为: 正式上线")
        urlStream = urlStream_p
    ######
    input("推流文件夹为：VideoFile\n按任意键 启动直播推流")
    doPushStream2()
    print("关闭直播推流")
